package com.example.moban.ui.fragment;

import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.view.menu.MenuAdapter;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import com.example.moban.R;
import com.example.moban.api.HuRequest;
import com.example.moban.base.BaseFragment;
import com.example.moban.beans.IncomeBean;
import com.example.moban.beans.LineChartBean;
import com.example.moban.utils.FeiLogUtil;
import com.example.moban.view.badgeview.BadgeView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.rzhd.coursepatriarch.common.api.base.BaseObserver;
import com.rzhd.coursepatriarch.common.constants.HttpConstants;
import com.rzhd.coursepatriarch.common.utils.CommonUtil;
import com.rzhd.coursepatriarch.common.utils.PhoneUtils;
import com.rzhd.coursepatriarch.common.utils.ToastUtils;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 个人中心
 * @author huling
 * @date: 2019/2/27.
 */
public class PersonCenterFragment extends BaseFragment {

    @BindView( R.id.fragment_person_center_header_img )
    ImageView headerImg;
    @BindView( R.id.fragment_person_center_name_text )
    AppCompatTextView nameText;
    @BindView( R.id.fragment_person_center_core_text )
    AppCompatTextView scoreText;
    @BindView( R.id.fragment_person_center_coursein_text )
    AppCompatTextView courseInText;
    @BindView( R.id.fragment_person_center_duration_text )
    AppCompatTextView durationText;
    @BindView( R.id.fragment_person_center_study_star_text )
    AppCompatTextView studyStarText;

    @BindView( R.id.fragment_person_class_center_recycer_view )
    RecyclerView classCenterRecycerView;
    @BindView( R.id.fragment_person_my_service_recycer_view )
    RecyclerView myServiceRecycerView;


    @BindView( R.id.person_center_my_message_btn )
    ImageView messageBtn;

    @BindView( R.id.fragment_person_center_sign_in_btn )
    AppCompatTextView signInBtn;
    @BindView( R.id.lineChart )
    LineChart lineChart;



//    private LineChart lineChart;
    private XAxis xAxis;                //X轴
    private YAxis leftYAxis;            //左侧Y轴
    private YAxis rightYaxis;           //右侧Y轴
    private Legend legend;              //图例
    private LimitLine limitLine;        //限制线
//  private MyMarkerView markerView;    //标记视图 即点击xy轴交点时弹出展示信息的View 需自定义






    private MenuAdapter classCenterMenuAdapter;
//    private int[] classCenterMenuIconArr = {
//            R.mipmap.icon_gm , R.mipmap.icon_wdxx , R.mipmap.icon_wdsc , R.mipmap.icon_wdpl
//    };
//    private String[] classCenterMenuNameArr;
//    private List<MenuItemBean> classCenterMenuList = new ArrayList<>();
//
//    private MenuAdapter myServiceMenuAdapter;
//    private int[] myServiceMenuIconArr = {
//            R.mipmap.icon_jfsc , R.mipmap.icon_wdbb , R.mipmap.icon_bzzx , R.mipmap.icon_lxwm,
//            R.mipmap.icon_yjfk, R.mipmap.category_assistant
//    };
//    private String[] myServiceMenuNameArr;
//    private List<MenuItemBean> myServiceMenuList = new ArrayList<>();
    private HuRequest huRequest;

    /**
     * 客服电话
     */
    private String servicePhone;

    @Override
    public void setContentView(FrameLayout contentView, Bundle savedInstanceState) {
        View view = LayoutInflater.from( getContext()).inflate(R.layout.fragment_person_center_layout , null );
        contentView.addView( view );
    }

    public static PersonCenterFragment newInstance(int  type , String objectId ) {
        PersonCenterFragment f = new PersonCenterFragment();
        Bundle b = new Bundle();
        b.putInt("libType", type );
        b.putString( "objectId" , objectId  );
        f.setArguments(b);
        return f;
    }


    @Override
    public void initView(View view) {
        huRequest = new HuRequest();
//        classCenterMenuNameArr = getResources().getStringArray( R.array.person_center_one_menu_arr );
//        myServiceMenuNameArr = getResources().getStringArray( R.array.person_center_two_menu_arr );
        initMenuDatas();


        initChart(lineChart);

        try {
//            String json = getResources().getString(R.string.ceshi_json);

            List<IncomeBean> list =new ArrayList<>();
            for (int i=0;i<15;i++){
                IncomeBean incomeBean=new IncomeBean();
                incomeBean.setTradeDate(String.valueOf(i+23));
                incomeBean.setValue(getNum(150));
                list.add(incomeBean);
            }

            showLineChart(list, "我的收益", Color.CYAN);
        }catch (Exception e){
            FeiLogUtil.e("fei",e.toString());
        }

    }


        /**
         * 生成一个0 到 count 之间的随机数
         * @param endNum
         * @return
         */
        public  int getNum(int endNum){
            if(endNum > 0){
                Random random = new Random();
                return random.nextInt(endNum);
            }
            return 0;
        }

    @Override
    public void initData() {

    }

    private void initMenuDatas(){
//        for( int i = 0 ; i < classCenterMenuNameArr.length; i++ ){
//            MenuItemBean bean = new MenuItemBean();
//            bean.setIcon( classCenterMenuIconArr[ i ]);
//            bean.setName( classCenterMenuNameArr[ i ]);
//            classCenterMenuList.add( bean );
//        }
//        for( int i = 0 ; i < myServiceMenuNameArr.length; i++ ){
//            MenuItemBean bean = new MenuItemBean();
//            bean.setIcon( myServiceMenuIconArr[ i ]);
//            bean.setName( myServiceMenuNameArr[ i ]);
//            myServiceMenuList.add( bean );
//        }
    }


    @Override
    public void onClick(View view) {

    }




    /**
     * 初始化图表
     */
    private void initChart(LineChart lineChart) {
        /***图表设置***/
        //是否展示网格线
        lineChart.setDrawGridBackground(false);
        //是否显示边界
        lineChart.setDrawBorders(true);
        //是否可以拖动
        lineChart.setDragEnabled(false);
        //是否有触摸事件
        lineChart.setTouchEnabled(true);
        //设置XY轴动画效果
        lineChart.animateY(2500);
        lineChart.animateX(1500);

        /***XY轴的设置***/
        xAxis = lineChart.getXAxis();
        leftYAxis = lineChart.getAxisLeft();
        rightYaxis = lineChart.getAxisRight();
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);
        rightYaxis.setAxisMinimum(0f);

        /***折线图例 标签 设置***/
        legend = lineChart.getLegend();
        //设置显示类型，LINE CIRCLE SQUARE EMPTY 等等 多种方式，查看LegendForm 即可
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(12f);
        //显示位置 左下方
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
    }




    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     *
     * @param lineDataSet 线条
     * @param color       线条颜色
     * @param mode
     */
    private void initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(3f);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setValueTextSize(10f);
        //设置折线图填充
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFormLineWidth(1f);
        lineDataSet.setFormSize(15.f);
        if (mode == null) {
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        } else {
            lineDataSet.setMode(mode);
        }
    }

    /**
     * 展示曲线
     *
     * @param dataList 数据集合
     * @param name     曲线名称
     * @param color    曲线颜色
     */
    public void showLineChart(List<IncomeBean> dataList, String name, int color) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            IncomeBean data = dataList.get(i);
            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */
            Entry entry = new Entry(i, (float) data.getValue());
            entries.add(entry);
        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        LineData lineData = new LineData(lineDataSet);
        lineChart.setData(lineData);
    }



    public  String getJson(String fileName) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = getActivity().getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }















}